package com.handtransaction.listener;

import com.handtransaction.entity.Category;
import com.handtransaction.service.CategoryService;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;

public class CategoriesListener implements ServletContextListener {
    private ServletContext sc = null;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        CategoryService categoryService = WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext()).getBean(CategoryService.class);
        List<Category> categories= categoryService.queryAllCategory();
        sc=servletContextEvent.getServletContext();
        sc.setAttribute("categories",categories);

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        sc = servletContextEvent.getServletContext();
        sc.removeAttribute("categories");
    }
}
